package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Client implements Runnable {
	private boolean run = true;
	private Server server;
	public String name;
	public Socket socket;
	public BufferedReader input;
	private PrintStream output;

	public Client(Server server, String name, Socket socket) {
		this.server = server;
		this.name = name;
		this.socket = socket;
		try {
			input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			output = new PrintStream(socket.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}

		new Thread(this).start();
	}

	public void run() {
		while (run) {
			try {
				if (!socket.isConnected()) {
					try {
						disconnect();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				String s = input.readLine();
				if (!s.equals(null)) {
					if (s.startsWith("[CLIENT_NAME]")) {
						name = s.replace("[CLIENT_NAME]", "");
						System.out.println("Name set to " + name);
					} else if (s.startsWith("[CLIENT_DISCONNECT]")) {
						try {
							disconnect();
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else if (s.startsWith("[CLIENT_MSG]")) {
						server.send(name, s.replace("[CLIENT_MSG]", ""));
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void disconnect() throws Exception {
		run = false;
		input.close();
		output.close();
		socket.close();
		System.out.println(name + " disconnected");
	}

	public void send(String name, String msg) {
		output.println("[" + name + "]: " + msg);
	}
}
